package com.supor.aiot.mine.ui.ips;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.view.View;

import com.android.baseconfig.base.DataApiResult;
import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.views.AppBasicDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.base.BaseMVVMFragment;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.helper.RefreshHelper;
import com.supor.aiot.common.interfaces.OnByItemFilterClickListener;
import com.supor.aiot.mine.R;
import com.supor.aiot.mine.bean.IpsBean;
import com.supor.aiot.mine.databinding.FragmentIpsListBinding;
import com.supor.aiot.mine.ui.adapter.IpsAdapter;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import static com.supor.aiot.mine.ui.ips.IpsActivity.idMap;

public class IpsListFragment extends BaseMVVMFragment<IpsListViewModel, FragmentIpsListBinding> {
    private AppBasicDialog deleteDialog;
    private IpsBean ipsBean;
    private IpsAdapter ipsAdapter;
    private boolean recordPage = true;

    public static IpsListFragment newInstance() {
        return new IpsListFragment();
    }

    @Override
    public int setContent() {
        return R.layout.fragment_ips_list;
    }

    @Override
    protected void initData() {
        viewModel.getIpsListData().observe(this, result -> {
            closeLoading();
            if (result instanceof Result.Error) {
                String error = ((Result.Error) result).getErrorMsg();
                Logc.i("onChanged: add ips failed: " + error);
                // ToastUtils.getInstance().showCustomToast(error);
            } else if (result instanceof Result.Success) {
                Logc.i("onChanged: get ips success");
                DataApiResult<IpsBean> apiResult = (DataApiResult<IpsBean>) result.getData();
                List<IpsBean> list = (List<IpsBean>) apiResult.rows;
                ((IpsActivity) activity).updateNum(apiResult.total, 0);
                if (!recordPage) {
                    if (list != null) {
                        List<IpsBean> tempList = new ArrayList<>();
                        for (IpsBean bean : viewModel.getIpsList()) {
                            if ("Y".equalsIgnoreCase(bean.ipsStatus)) {
                                tempList.add(bean);
                            }
                        }
                        ipsAdapter.addData(tempList);
                    }
                } else {
                    ipsAdapter.addData(list);
                }
                if (ipsAdapter.getData().size() == 0) {
                    bindingView.tvNone.setVisibility(View.VISIBLE);
                } else {
                    bindingView.tvNone.setVisibility(View.GONE);
                }
                bindingView.rcvIps.setRefreshing(false);


//                List<IpsBean> list = new ArrayList<>();
//                for (int i = 0; i < 10; i++) {
//                    list.add(new IpsBean());
//                }
//                ipsAdapter.addData(list);
//                bindingView.rcvIps.setRefreshing(false);
            }
        });
        viewModel.getDeleteResult().observe(this, result -> {
            closeLoading();
            if (result instanceof Result.Error) {
                ToastUtils.getInstance().showCustomToast(((Result.Error) result).getErrorMsg());
            } else if (result instanceof Result.Success) {
                ipsAdapter.removeData((Integer) result.getData());
                if (ipsAdapter.getData().size() == 0) {
                    bindingView.tvNone.setVisibility(View.VISIBLE);
                } else {
                    bindingView.tvNone.setVisibility(View.GONE);
                }
                bindingView.rcvIps.setRefreshing(false);
            }
        });
        viewModel.getLoadMoreData().observe(this, s -> bindingView.rcvIps.loadMoreEnd());
        viewModel.ipsList(false);
    }

    @Override
    protected void loadData() {
        super.loadData();
    }

    @Override
    protected void initEvent() {

        // BindDevice布局管理器
        RefreshHelper.initLinear(bindingView.rcvIps,
                getResources().getDimensionPixelSize(R.dimen.dp_2));
        bindingView.rcvIps.setRefreshEnabled(true);
        bindingView.rcvIps.setOnRefreshListener(this::refresh);
        bindingView.rcvIps.setLoadMoreEnabled(true);
        bindingView.rcvIps.setOnLoadMoreListener(() -> {
            if (viewModel != null) {
                viewModel.ipsList(true);
            }
        }, 1000);
        // bindingView.rcvIps.setNotFullScreenNoLoadMore();
        // bindingView.rcvIps.setHasFixedSize(true);
        bindingView.rcvIps.setNestedScrollingEnabled(true);
        // ViewCompat.setNestedScrollingEnabled(bindingView.rcvIps, false);
        ipsAdapter = new IpsAdapter(new ArrayList<>());
        ipsAdapter.setIdMap(idMap);
        bindingView.rcvIps.setOnItemClickListener(new OnByItemFilterClickListener() {
            @Override
            protected void onSingleClick(@NonNull BaseQuickAdapter<?, ?> adapter, View v,
                                         int position) {
                Logc.e("onItemClick: position: " + position);
                List<IpsBean> list1 = ipsAdapter.getData();
                IpsBean ipsBean = list1.get(position);
                Intent intent = new Intent(activity, IpsDetailActivity.class);
                intent.putExtra(Constants.Key.BEAN, ipsBean);
                startActivity(intent);
            }
        });
        bindingView.rcvIps.setOnItemLongClickListener((v, position) -> {
            showDeleteDialog(position);
            return false;
        });
        bindingView.rcvIps.setAdapter(ipsAdapter);

    }

    protected void refresh() {
        if (viewModel != null) {
            bindingView.rcvIps.loadMoreComplete();
            ipsAdapter.clear();
            ipsAdapter.setNewData(new ArrayList<>());
            ipsAdapter.notifyDataSetChanged();
            viewModel.ipsList(false);
        }
    }

    @SuppressLint("CheckResult")
    public void click(View v) {
        int id = v.getId();
        if (id == R.id.tv_record) {
            recordPage = true;
            ipsAdapter.setNewData(viewModel.getIpsList());
            if (ipsAdapter.getData().size() == 0) {
                bindingView.tvNone.setVisibility(View.VISIBLE);
            } else {
                bindingView.tvNone.setVisibility(View.GONE);
            }
        } else if (id == R.id.tv_record_accept) {
            recordPage = false;
            if (viewModel.getIpsList() != null) {
                List<IpsBean> list = new ArrayList<>();
                for (IpsBean bean : viewModel.getIpsList()) {
                    if ("Y".equalsIgnoreCase(bean.ipsStatus)) {
                        list.add(bean);
                    }
                }
                ipsAdapter.setNewData(list);
                if (ipsAdapter.getData().size() == 0) {
                    bindingView.tvNone.setVisibility(View.VISIBLE);
                } else {
                    bindingView.tvNone.setVisibility(View.GONE);
                }
            }
        }
    }

    // @Override
    // public void updateNetStatus(int type) {
    // }

    private void showDeleteDialog(int pos) {
        if (deleteDialog != null && deleteDialog.isShowing()) {
            deleteDialog.dismiss();
        }
        AppBasicDialog.Builder builder = new AppBasicDialog.Builder(activity, false);
        builder.setTitle(R.string.delete);
        builder.setMessage("是否删除创意？");
        builder.setPositiveButton(R.string.sure, (dialog, which) -> {
            showLoading();
            viewModel.deleteIps(ipsAdapter.getItemData(pos), pos);
            dialog.cancel();
        });
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.cancel());
        deleteDialog = builder.create();
        deleteDialog.setCancelable(false);
        deleteDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.REQUEST_CODE) {

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus3.getInstance().unregister(this.getClass());
    }
}
